<template>
  <div>
    <div class="searchForm bk-edit">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="ruleJ"
        label-width="100px"
        class="bk-form"
      >
        <div
          v-for="(item, index) in formHead"
          :key="index"
          class="bk-item"
          :style="{
            width:
              item.width ||
              (item.type == 'search' && item.type == 'auto') ||
              config.autoWidth ||
              '25%',
          }"
        >
          <!-- input输入框:class="{ 'no-border': item.type == 'upload' }" -->
          <el-form-item
            v-if="item.type == 'input' || item.type == 'textarea'"
            :prop="item.prop"
            :class="item.class"
            :label="item.label"
            :label-width="
              $px2rem(item.labelWidth) ||
              $px2rem(config.labelWidth) ||
              $px2rem('100px')
            "
          >
            <div>
              <el-input
                v-model.trim="ruleForm[item.prop]"
                size="small"
                :type="item.type"
                :disabled="item.disabled"
                :clearable="!item.clearable"
                :maxlength="item.maxlength || 255"
                :placeholder="item.placeholder || `请输入${item.label}`"
                @input="item.input ? item.input($event, item) : null"
                @blur="item.blur ? item.blur($event, item) : null"
                @focus="item.focus ? item.focus($event, item) : null"
                @keyup.enter.native="
                  item.enterEvent ? item.enterEvent($event, item) : null
                "
              />
            </div>
          </el-form-item>
          <el-form-item
            v-if="item.type == 'radio'"
            :prop="item.prop"
            :class="item.class"
            :label="item.label"
          >
            <div>
              <el-radio-group v-model="ruleForm[item.prop]">
                <el-radio
                  v-for="(ele, ind) in item.options"
                  :key="ind"
                  :label="ele.value"
                  >{{ ele.label }}</el-radio
                >
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item v-if="item.type == 'checkbox'" :prop="item.prop">
            <div>
              <el-checkbox size="small" v-model="ruleForm[item.prop]">{{
                item.text
              }}</el-checkbox>
            </div>
          </el-form-item>
          <el-form-item v-if="item.type == 'slot'">
            <slot :name="item.prop"></slot>
          </el-form-item>
          <!-- 下拉选择框 -->
          <el-form-item
            v-if="item.type == 'select'"
            :label="item.label"
            :prop="item.prop"
            :class="item.class"
            :label-width="
              $px2rem(item.labelWidth) ||
              $px2rem(config.labelWidth) ||
              $px2rem('100px')
            "
          >
            <div>
              <el-select
                v-model="ruleForm[item.prop]"
                size="small"
                :popper-append-to-body="false"
                :placeholder="item.placeholder || `请选择${item.label}`"
                :disabled="item.disabled"
                filterable
                default-first-option
                :remote="item.remote || false"
                :remote-method="item.remoteMethod || null"
                :clearable="!item.clearable"
                :collapse-tags="item.collapseTags || false"
                @change="item.change ? item.change(ruleForm[item.prop]) : null"
                @clear="item.clear ? item.clear() : null"
              >
                <el-option
                  v-for="(ele, ind) in item.options"
                  :key="ind"
                  :label="
                    item.props && Object.keys(item.props).length
                      ? ele[item.props.label]
                      : ele.label
                  "
                  :value="
                    item.props && Object.keys(item.props).length
                      ? ele[item.props.value]
                      : ele.value
                  "
                />
              </el-select>
            </div>
          </el-form-item>
          <!-- 级联 -->
          <el-form-item
            v-if="item.type == 'cascader'"
            :label="item.label"
            :prop="item.prop"
            :class="item.class"
            :label-width="
              $px2rem(item.labelWidth) ||
              $px2rem(config.labelWidth) ||
              $px2rem('100px')
            "
          >
            <div>
              <el-cascader
                v-model="ruleForm[item.prop]"
                :placeholder="item.placeholder || `请选择${item.label}`"
                size="small"
                :append-to-body="false"
                :options="item.options"
                :props="item.props"
                :ref="item.refs || item.prop"
                :show-all-levels="item.showAllLevels || false"
                filterable
                :clearable="!item.clearable"
                :collapse-tags="item.collapseTags"
                @change="item.change ? item.change() : null"
              />
            </div>
          </el-form-item>
          <!-- 时间 -->
          <el-form-item
            v-if="['date', 'daterange', 'datetimerange'].includes(item.type)"
            :label="item.label"
            :prop="item.prop"
            :class="item.class"
            :label-width="
              $px2rem(item.labelWidth) ||
              $px2rem(config.labelWidth) ||
              $px2rem('100px')
            "
          >
            <div>
              <el-date-picker
                v-model="ruleForm[item.prop]"
                size="small"
                :type="item.type"
                :format="item.format || 'yyyy-MM-dd'"
                :value-format="item.valueFormat || 'yyyy-MM-dd'"
                :start-placeholder="item.startPlaceholder || '开始日期'"
                :end-placeholder="item.endPlaceholder || '结束日期'"
                :placeholder="item.placeholder || `请选择${item.label}`"
                :picker-options="item.pickerOptions"
                :clearable="!item.clearable"
                :disabled="item.disabled"
                @change="item.change ? item.change(ruleForm[item.prop]) : null"
              />
            </div>
          </el-form-item>
          <!-- 计数器 -->
          <el-form-item
            v-if="item.type == 'inputNumber'"
            :label="item.label"
            :prop="item.prop"
            :class="item.class"
            :label-width="
              $px2rem(item.labelWidth) ||
              $px2rem(config.labelWidth) ||
              $px2rem('100px')
            "
          >
            <div :class="{ unitItem: item.unit }">
              <el-input
                v-model="ruleForm[item.prop]"
                size="small"
                type="number"
                min="0"
                :clearable="!item.clearable"
                :disabled="item.disabled"
                :placeholder="item.placeholder || `请输入${item.label}`"
                @input="item.input ? item.input() : null"
              ></el-input>
              <span class="unitBox" v-if="item.unit">
                {{ item.unit }}
              </span>
            </div>
          </el-form-item>
          <!-- 计数器范围 -->
          <el-form-item
            v-if="item.type == 'numrange'"
            :label="item.label"
            :class="item.class"
            :label-width="
              $px2rem(item.labelWidth) ||
              $px2rem(config.labelWidth) ||
              $px2rem('100px')
            "
            :required="ruleJ[item.minprop]"
          >
            <div>
              <el-col :span="11">
                <el-form-item :prop="item.minprop">
                  <el-input
                    size="small"
                    @input="item.input ? item.input() : null"
                    type="number"
                    :clearable="!item.clearable"
                    :disabled="item.disabled"
                    v-model="ruleForm[item.minprop]"
                    :placeholder="item.placeholder || `请输入最小值`"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item :prop="item.maxprop">
                  <el-input
                    size="small"
                    @input="item.input ? item.input() : null"
                    type="number"
                    :clearable="!item.clearable"
                    :disabled="item.disabled"
                    v-model="ruleForm[item.maxprop]"
                    :placeholder="item.placeholder || `请输入最大值`"
                  ></el-input>
                </el-form-item>
              </el-col>
            </div>
          </el-form-item>

          <!-- 纯文本 -->
          <el-form-item
            v-if="item.type == 'text'"
            :label="item.label"
            :prop="item.prop"
            :class="item.class"
            :label-width="
              $px2rem(item.labelWidth) ||
              $px2rem(config.labelWidth) ||
              $px2rem('100px')
            "
          >
            <div :class="item.textClass" class="bk-text-span">
              <span v-if="item.formatter">{{ item.formatter() }}</span>
              <span v-else>{{ ruleForm[item.detailProp || item.prop] }}</span>
            </div>
          </el-form-item>
        </div>
        <el-form-item class="btn-item" v-if="searchFlag">
          <div>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="info" plain @click="resetForm">重置</el-button>
            <el-button
              v-if="config.seniorFlag"
              type="primary"
              plain
              @click="seniorSearch"
              >高级查询</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <div class="hanle_box" v-if="dataJ.length > config.dataLen">
        <span class="handler" @click="handleClick"
          >{{ flag ? "展开" : "收起"
          }}<i :class="flag ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i
        ></span>
      </div>
    </div>
    <!-- <SeniorSearchForm
      v-if="disSeniorFlag"
      ref="seniorSearchForm"
      :dictValue="dictValue"
      v-model="dynamicValidateForm"
    /> -->
  </div>
</template>

<script>
// import mixins from './mixins'
/**
 * dataJ 数据源
 * ruleJ 表单验证数据源
 * type 详情（detail） || 新增(add)
 * ruleForm 表单数据
 */

// import uploadFile from "@/commom/uploadFile/upload.vue";
// import SeniorSearchForm from "./seniorSearchForm.vue";

export default {
  name: "EditOrDetail",
  components: {
    // uploadFile,
    // SeniorSearchForm,
  },
  model: {
    prop: "ruleForm",
    event: "formChange",
  },
  props: {
    // 数据源
    dataJ: {
      type: Array,
      default: () => [],
    },
    // 表单规则
    ruleJ: {
      type: Object,
      default: () => ({}),
    },
    // 表单数据
    ruleForm: {
      type: Object,
      default: () => ({}),
    },
    // 配置
    config: {
      type: Object,
      default: () => {
        return {
          type: "add",
          autoWidth: "25%",
          dataLen: 7,
          seniorFlag: false,
        };
      },
    },
    isAdd: {
      type: Boolean,
      default: true,
    },
    searchFlag: {
      type: Boolean,
      default: true,
    },
    conditionOpts: {
      type: Array,
      default: () => {
        [];
      },
    },
    symbolOpts: {
      type: Array,
      default: () => {
        [];
      },
    },
    // 高级查询字典值
    dictValue: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      ruleFormList: ["select"], // 需要获取name值的插件
      ruleFormName: {}, // ruleForm字段对应name值
      formHead: [],
      flag: true,
      disSeniorFlag: false,
      dynamicValidateForm: {
        domains: [
          {
            searchProperty: "",
            searchRule: "",
            searchValue: "",
            searchType: "and",
            key: Date.now(),
            type: "",
          },
        ],
      },
    };
  },
  computed: {},
  watch: {
    dataJ: {
      handler(val) {
        if (this.flag) {
          this.formHead = val.slice(0, this.config.dataLen);
        } else {
          this.formHead = val;
        }
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.setInitValue();
    });
  },
  methods: {
    $px2rem(px) {
      console.log(px)
      if (!px) {
        return false;
      } else {
        if (/%/gi.test(px)) {
          // 有百分号%，特殊处理，表述pc是一个有百分号的数，比如：90%
          return px;
        } else {
          return parseFloat(px) / 100 + "rem";
        }
      }
    },
    handleClick() {
      this.flag = !this.flag;
      if (this.flag) {
        this.formHead = this.dataJ.slice(0, this.config.dataLen);
      } else {
        this.formHead = this.dataJ;
      }
      this.$bus.emit("handleClick");
    },
    // ruleForm初始化
    setInitValue() {
      let ruleForm = {};
      this.dataJ.forEach((el) => {
        if (el.type != "render") {
          if (el.prop) {
            if (el.defaultVal) {
              ruleForm[el.prop] = el.defaultVal;
            } else {
              ruleForm[el.prop] = "";
            }
          }
        }
      });
      this.$emit("formChange", { ...ruleForm, ...this.ruleForm });
    },
    // 清除表单验证
    clearVaild(arr) {
      if (arr && arr.length) {
        arr.forEach((el) => {
          this.$refs.ruleForm.clearValidate(el);
        });
      } else {
        this.$refs.ruleForm.clearValidate();
      }
    },
    signalVaild(fileValue) {
      this.$refs.ruleForm.validateField(fileValue);
    },
    async search() {
      if (this.disSeniorFlag) {
        this.$nextTick(async () => {
          if (await this.$refs.seniorSearchForm.validateForm()) {
            await this.$emit("formChange", {
              ...this.ruleForm,
              seniorList: this.dynamicValidateForm.domains,
            });
            this.$emit("search-form");
          }
        });
      } else {
        this.$emit("formChange", { ...this.ruleForm, seniorList: [] });
        this.$emit("search-form");
      }
    },
    seniorSearch() {
      this.disSeniorFlag = !this.disSeniorFlag;
      this.$bus.emit("handleClick");
    },
    resetForm() {
      this.dataJ.forEach((el) => {
        if (!el.noReset) {
          if (this.ruleForm[el.prop] instanceof Array) {
            this.ruleForm[el.prop] = [];
          } else if (this.ruleForm[el.prop] instanceof Object) {
            this.ruleForm[el.prop] = {};
          } else {
            if (el.type == "numrange") {
              this.ruleForm[el.minprop] = "";
              this.ruleForm[el.maxprop] = "";
            } else {
              this.ruleForm[el.prop] = "";
            }
          }
        }
        if (el.defaultVal || el.defaultVal === 0 || el.defaultVal === null) {
          this.ruleForm[el.prop] = el.defaultVal;
        }
      });
      this.disSeniorFlag && this.$refs.seniorSearchForm.resetDomain();
      this.disSeniorFlag = false;
      this.$bus.emit("handleClick");
      this.$emit("reset-form");
      // this.$nextTick(() => {
      //   this.$emit("search-form");
      // });
      this.search();
    },
    // 表单验证
    formValid() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve(true);
          } else {
            Object.keys(this.ruleJ).some((el) => {
              let obj = this.dataJ.find((item) => item.prop == el);
              let label = obj && (obj.label || obj.name);
              if (
                Array.isArray(this.ruleForm[el]) &&
                !this.ruleForm[el].length
              ) {
                label &&
                  this.$message({
                    type: "warning",
                    duration: 5000,
                    message: `请填写${label}`,
                  });
                return true;
              } else if (!this.ruleForm[el]) {
                label &&
                  this.$message({
                    type: "warning",
                    duration: 5000,
                    message: `请填写${label}`,
                  });
                return true;
              }
            });
            reject(false);
          }
        });
      });
    },
    // 获取对应prop的name值
    async getValueName() {
      this.ruleFormName = {};
      await this.dataJ.forEach((el) => {
        if (this.ruleFormList.includes(el.type)) {
          let obj = el.options.find(
            (re) =>
              (el.props && re[el.props.value] == this.ruleForm[el.prop]) ||
              re.value == this.ruleForm[el.prop]
          );
          let name = obj ? (el.props ? obj[el.props.label] : obj.label) : "";
          let label = el.prop + "Name";
          this.$set(this.ruleFormName, [label], name);
        }
      });
      return this.ruleFormName;
    },
  },
};
</script>
<style lang="less" scoped>
.bk-detail {
  .bk-form {
    .bk-item {
      border-bottom: 1px solid #ccc;
      .bk-text-span {
        overflow: hidden;
        height: 40px;
        line-height: 40px;
      }
    }
  }
}
.searchForm {
  // overflow: hidden;
  display: flex;
  padding-top: 16px;
  background-color: #fff;
  border-bottom: 1px solid #e5e6eb;
  // margin-bottom: 10px;
  .hanle_box {
    position: relative;
    display: inline-block;
    width: 50px;
    margin-left: 5px;
    .handler {
      color: #206bff;
      font-size: 12px;
      position: absolute;
      top: 10px;
      left: 0;
      cursor: pointer;
    }
  }

  .bk-form {
    width: 100%;
    .no-border {
      border: none;
    }
    .bk-item {
      // padding: 0 1%;
      margin-bottom: 15px;
      padding-right: 1%;
      display: inline-block;
      box-sizing: border-box;
      vertical-align: bottom;
      ::v-deep .el-form-item {
        margin-bottom: 0px;
      }
      .el-form-item__label {
        min-height: 27px;
      }
      ::v-deep .el-date-editor {
        width: 100%;
      }
      ::v-deep .el-form-item__content {
        min-width: 60px;
      }
      ::v-deep input[type="number"] {
        padding-right: 10px;
      }
      .el-select {
        width: 100%;
      }
      .el-cascader {
        width: 100%;
      }
    }
    .bk-text {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      height: 40px;
      line-height: 40px;
    }
    .bk-text-span {
      overflow: initial;
      height: 40px;
      line-height: 40px;
    }
    .picture {
      .bk-item {
        border: none;
      }
    }
    ::v-deep .el-form-item.btn-item {
      display: inline-block;
      margin: 0;
      margin-bottom: 15px;
      .btn-box {
        display: inline-block;
        margin: 0 10px;
      }
      .el-form-item__content {
        margin-left: 0px !important;
      }
      .el-button {
        margin-right: 14px;
      }
    }
    .line {
      text-align: center;
    }
  }
  .unitItem {
    display: flex;
    .unitBox {
      margin-left: 3px;
      white-space: nowrap;
    }
  }
}
</style>
<style>
input::-webkit-outer-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}
input[type="number"] {
  -moz-appearance: textfield;
}
@media screen and (max-width: 1366px) {
  .searchForm .el-form-item__label {
    line-height: 40px !important;
  }
}
</style>
